package com.yanqu.road;

import com.yanqu.road.define.YanQuNettyDefine;
import com.yanqu.road.initialize.YanQuCHInitializer;
import com.yanqu.road.connect.ServerConnectionGroup;
import com.yanqu.road.netty.server.NettyParamOperator;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.util.AttributeKey;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class NettyMgr {

	private static Logger logger = LogManager.getLogger(NettyMgr.class.getName());

	public static final AttributeKey<ServerConnectionGroup> LINKED_CLIENT = AttributeKey.valueOf(YanQuNettyDefine.LINKED_CLIENT_KEY);

	private static ChannelFuture channelFuture;
	private static EventLoopGroup bossGroup;
	private static EventLoopGroup workGroup;

	public static boolean start(int wsPort, ChannelHandler channelHandler) {
		try {
			int threadsNum = Runtime.getRuntime().availableProcessors();
			bossGroup = new NioEventLoopGroup(threadsNum);
			workGroup = new NioEventLoopGroup(threadsNum * 4);
			ServerBootstrap serverBootstrap = getServerBootstrap(channelHandler);
			channelFuture = serverBootstrap.bind(wsPort);
			channelFuture.sync();

			return true;

		} catch (Exception e) {
			logger.error("netty 初始化失败:", e);
			return false;
		}
	}

	private static ServerBootstrap getServerBootstrap(ChannelHandler handler) {
		ServerBootstrap serverBootstrap = new ServerBootstrap();
		serverBootstrap.group(bossGroup, workGroup);
		serverBootstrap.channel(NioServerSocketChannel.class);
		serverBootstrap.childHandler(new YanQuCHInitializer(handler));
		NettyParamOperator.buildWebsocketBootstrapOptions(serverBootstrap);
		return serverBootstrap;
	}

	public static void stop() {

	}

	public static void newStop() {
		try {
			channelFuture.channel().close().sync();
		} catch (Exception e) {
			logger.error("netty关闭异常", e);
		}
	}
}
